import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'filter'
})

export class FilterPipe implements PipeTransform {

    transform(items: any[], key, field): any {

        let result: any[];
        if (key == null || key === '' || key === undefined) {
            return items;
        } else {
            const regHz = /^[\u4E00-\uFA29]+$/;   // 中文;英文:[\uE7C7-\uE7F3]
            if (regHz.test(key)) {
                result = items.filter(n => {
                    return JSON.stringify(n.n).search(key) > 0;
                });
            } else {
                if (key.length === 1) {
                    result = items.filter(n => {
                        return n.p.substring(0, 1) === key; // 单个字母 匹配首字母
                    });
                } else {
                    result = items.filter(n => {
                        return JSON.stringify(n.p).search(key.toLowerCase()) > 0; // 优化搜索速度
                    });
                }
            }
        }
        return result;
    }
}
